const {
  CODE_ERROR,
  CODE_SUCCESS,
  CODE_TOKEN_EXPIRED
} = require('../utils/constant')
const { json } = require('body-parser')

class Result {
  constructor(data, msg = '操作成功', options) {
    this.data = null  // 默认 data 为空
    // 一个参数也没有传，默认为成功
    if (arguments.length === 0) {
      this.msg = '操作成功'
    }
    // 传递一个参数，说明 data 的部分就是 msg ，所以这里把 data 赋值给 msg
    else if (arguments.length === 1) {
      this.msg = data
    } else {
      this.data = data
      this.msg = msg
      if (options) {
        this.options = options
      }
    }
  }
  createResult(){
    // code 不存在，就默认 code 为 0
    if (!this.code) {
      this.code = CODE_SUCCESS
    }
    let base = {
      code: this.code,
      msg: this.msg
    }
    if (this.data) {
      base.data = this.data
    }
    if (this.options) {
      base = { ...base, ...this.options }
    }
    console.log(base)
    return base
  }
  
  json(res) {
    res.json(this.createResult())
  }

  success(res) {
    this.code = CODE_SUCCESS
    this.json(res)
  }

  fail(res) {
    this.code = CODE_ERROR
    this.json(res)
  }

  // token 错误
  jwtError(res) {
    this.code = CODE_TOKEN_EXPIRED
    this.json(res)
  }
}

module.exports = Result
